import { observable, action } from "mobx";
import { each, uniqueId } from 'lodash';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import u from "../utils";
import API from '../apis/cuspath';
import NodeFrom from "./entity/NodeForm";
import { displayTypes } from "../constants/app";
import { TaskViewPageType } from "../constants/task";
import CombineSetDialogStore from "./dialog/combineSetDialogStore";
import FieldPropDialogStore from './dialog/FieldPropDialogStore';
import TemplateBrowserStore from "./dialog/templateBrowserStore";
import OperateMenuDialogStore from "./dialog/operateMenuDialogStore";
import BeforeNodeOperateDialogStore from "./dialog/beforeNodeOperateDialogStore"
import JoinCubeDialogStore from "./dialog/joinCubeDialogStore";
import { getPathByAppId } from "../apis/path";
import NodeModalStore from "./dialog/NodeModalStore";
import DynamicNodePreviewDialogStore from "./dialog/DynamicNodePreviewDialogStore"
import { formInfo } from '../components/designer/path/operatorData';
const _API = u.api('custompath');
import { WeaLocaleProvider,WeaTools } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

const dynamicNodeFieldKeys = {
    uuid: 'uuid',
    nodeType: 'nodeType',
    operatorType: 'operatorType',
    tablename: 'tablename',
    tablekey: 'tablekey',
    showfield: 'showfield',
    hrmField: 'hrmField',
    sqlWhere: 'sqlWhere',
    isrecursion: 'isrecursion',
    tablesup: 'tablesup',
    relationtype: 'relationtype',
    hrmresource: 'hrmresource',
    hrmdepartment: 'hrmdepartment',
    hrmsubcompany: 'hrmsubcompany',
    rootids: 'rootids',
    supnodefield: 'supnodefield',
    nodefield: 'nodefield',
}

export default class PathDesignerStore {
    @observable data;
    @observable versionNode;
    @observable node;
    @observable path;
    @observable showRight = true;
    @observable rightLoading = false;
    @observable readonly = false;
    @observable nodeForm = new NodeFrom();
    @observable childOpreator = [];

    @observable combine = '1';
    @observable layout = '0';
    @observable scale = 1;

    @observable pathType = 0;
    @observable dynamicNode;
    @observable hasChildren = false;


    @observable leftWidth = 3;
    @observable rightWidth = 6;

    @observable combineSetDialogStore;
    @observable fieldPropDialogStore;
    @observable templateBrowserStore = new TemplateBrowserStore('custompath');
    @observable nodeModalStore;
    @observable loading = false;

    @observable operateMenuDialogStore;
    @observable beforeNodeOperateDialogStore;
    @observable joinCubeDialogStore;


    @observable addDynamicChildDialogStore;
    @observable dynamicNodeForm = new WeaForm();
    @observable itemType = '0';
    @observable parentNodeType;
    @observable parentOperateType;
    @observable parentTableName;
    @observable operatorForm;
    @observable operatorDataSource = [];
    @observable selectedRowKeysAllPages = [];

    @observable dynamicNodePreviewDialogStore;
    @observable disableAll = false;

    constructor() {
        message.config({ top: 60 });
        this.nodeForm.parent = () => this;
        this.templateBrowserStore.title = getLabel('503349', '选择路径');
        this.combineSetDialogStore = new CombineSetDialogStore();
        this.fieldPropDialogStore = new FieldPropDialogStore(this);
        this.operateMenuDialogStore = new OperateMenuDialogStore(this);
        this.beforeNodeOperateDialogStore = new BeforeNodeOperateDialogStore(this);
        this.joinCubeDialogStore = new JoinCubeDialogStore(this);
        this.nodeModalStore = new NodeModalStore(this);
        this.dynamicNodePreviewDialogStore = new DynamicNodePreviewDialogStore(this);
        each(dynamicNodeFieldKeys, action((value, key) => {
            this.dynamicNodeForm.add('', { key });
            if (key === 'hreflink') {
                this.dynamicNodeForm.add('', { key: 'hreflinkType' });
                this.dynamicNodeForm.add('', { key: 'hreflinkUrl' });
            } else if (key === 'operatorType') {
                this.dynamicNodeForm.$(key).set('0');
            } 
        }));
    }
    @action hideNodeForm = () => {
        this.showRight = false;
    }
    @action changeLayout = (layout) => {
        this.layout = layout;
    }
    @action changeScale = (scale) => {
        this.scale = scale;
    }
    @action
    addNodes = (nodeid, ids, img) => {
        _API('addCustomNodes', { type: "post", data: { nodeid, ids, pathid: this.path.id, hreflink: JSON.stringify(this.nodeForm.defaultPage), img } })
            .then((path) => {
                this.setPath(path);
                this.hasChildren = true;
                message.success(getLabel('502231', '保存成功'));
            });
    }
    @action allChildOpreator = (nodeid) => {
        this.childOpreator = [];
        return API.allChildOpreator(nodeid);
    }
    @action setChildOpreator = (childOpreator) => {
        this.childOpreator = childOpreator;
    }
    @action saveAsTemplate = (img) => {
        this.loading = true;
        API.saveAsTemplate({ pathid: this.path.id, img }).then(() => {
            this.loading = false;
            message.success(getLabel('502231', '保存成功'));
        });
    }
    @action loadTemplate = ({ id = 0 } = {}) => {
        this.loading = true;
        API.loadTemplate({ id, pathid: this.path.id, hreflink: JSON.stringify(this.nodeForm.defaultPage) }).then(this.setPath);
    }
    @action
    deleteNode = (nodeid) => {
        _API('deleteCustomNode', { data: { nodeid } }).then(this.afterDelete);
    }
    @action
    deleteChildren = (nodeid) => {
        API.deleteChildren(nodeid).then((path) => {
            this.setPath(path);
            this.hasChildren = false;
            this.setChildOpreator([])
            message.success(getLabel('502230', '删除成功'));
        });
    }
    @action afterDelete = (path) => {
        this.setPath(path);
        this.nodeForm = new NodeFrom();
        this.nodeForm.parent = () => this;
        this.showRight = false;
        message.success(getLabel('502230', '删除成功'));
    }
    @action
    saveNode = () => {
        const nodeFormParams = this.nodeForm.toJSON();
        const [pageType, pageUrl, pageId] = JSON.parse(nodeFormParams.hreflink);
        if (pageType === TaskViewPageType.EXCEL && (!pageId || !nodeFormParams.sheetIds)) {
            message.error(getLabel('515360', '未选择表格和sheet页'));
            return;
        }
        if (nodeFormParams.synchronizeType === '2' && nodeFormParams.synchronizeNodeId === null) {
            message.error(getLabel('512015', '未指定同步节点'));
            return;
        }
        //this.loading = true;
        // API.saveNode(nodeFormParams).then((path) => {
        //     this.loading = false;
        //     message.success(getLabel('502231','保存成功'));
        //     this.setPath(path);
        // });
        const values = this.dynamicNodeForm.values();
        if (this.checkParams(values, nodeFormParams.operatorSetType)) {
            this.loading = true;
            const diffs = this.getParams();
            API.saveNode({ pathType:this.pathType,...nodeFormParams, ...diffs, operators: JSON.stringify(this.operatorDataSource) }).then((path) => {
                this.loading = false;
                message.success(getLabel('502231', '保存成功'));
                this.setPath(path);
            }).catch(e=>{
                this.loading = false;
            });
        }
    }
    @action
    openNode = (node, hasChildren) => {
        this.showRight = true;
        this.rightLoading = true;
        this.nodeForm.reportTypeVisible = hasChildren;
        this.hasChildren = hasChildren;
        API.versionNode(node.id).then(this.initNodeForm)
    }
    @action
    initNodeForm = (node) => {
        this.node = node;
        this.disableAll = node.disableAll;
        this.rightLoading = false;
        if (this.parent().app.displayType === displayTypes.FORM) {
            this.nodeForm.hreflinkObjLabel = getLabel('502896', '表单');
            this.nodeForm.hreflinkObjOptions = this.nodeForm.hreflinkObjOptions.filter(d => d.key !== TaskViewPageType.EXCEL);
            this.nodeForm.defaultPage = [TaskViewPageType.FORM];
        } else {
            this.nodeForm.hreflinkObjLabel = getLabel('502895', '表格');
            this.nodeForm.defaultPage = [TaskViewPageType.EXCEL, '', this.parent().selectedKey];
            this.nodeForm.hreflinkObjOptions = this.nodeForm.hreflinkObjOptions.filter(d => d.key !== TaskViewPageType.FORM);
        }
        this.nodeForm.init(node, this.parent().excelPages);
        if(this.pathType==3) this.initDynamicNodeInfo(node);
    }
    @action
    initPath = (params, readonly) => {
        this.params = params;
        this.readonly = readonly;
        getPathByAppId(params).then(path => {
            this.setPath(path);
        });
    }

    @action
    setPath = (path) => {
        this.loading = false;
        this.combine = path.combine;
        this.node = path.node;
        this.versionNode = path.versionNode;
        this.pathType = path.pathType;
        delete path.node;
        delete path.versionNode;
        this.path = path;
    }

    @action toggleCombine = (combine) => {
        this.combine = combine;
        API.toggleCombine({ pathid: this.path.id, combine });
    }

    @action openPathTemplateDialog = () => {
        this.templateBrowserStore.open();
    }


    @action fixedWidth = (clientWidth) => {
        const all = this.leftWidth + this.rightWidth;
        const per = clientWidth / all;
        this.leftWidth = per * this.leftWidth;
        this.rightWidth = per * this.rightWidth;
    }
    @action onLeftResize = (e, { size: { width } }) => {
        this.rightWidth = this.leftWidth + this.rightWidth - width;
        this.leftWidth = width;
        this.treeRef.resize();
    }

    @action showNodeModal = (id, parentid) => {
        if (id) {
            this.nodeModalStore.init(id, parentid)
            this.nodeModalStore.title = getLabel('503350', '设置节点');

        }
        this.nodeModalStore.open();
    }

    @action synchronizeNode = (ids) => {
        API.synchronizeNode({ nodeid: this.nodeForm.id, synchronizeNodeId: ids }).then((path) => {
            message.success(getLabel('502231', '保存成功'));
        });
    }

    /**动态节点信息相关 start*/
    @action initDynamicNodeInfo = (node) => {
        if (node.parentid == 0) node.uuid = 'root'
        this.parentTableName = node.parentTableName
        this.parentNodeType = node.parentNodeType;
        this.parentOperateType = node.parentOperateType;
        this.dynamicNodeForm.resetForm();
        if (node.parentNodeType === '1') {
            this.dynamicNodeForm.$('nodeType').set('1');
            this.dynamicNodeForm.$('operatorType').set('0');
            this.itemType = '6';
            this.dynamicNodeForm.$('relationtype').set('1');
        }
        switch (node.nodeType) {
            case '0': this.itemType = '0'; break;
            case '1': this.itemType = '6'; break;
        }
        switch (node.operatorType) {
            case '0': this.itemType = '6'; break;
            case '1': this.itemType = '7'; break;
            case '2': this.itemType = '11'; break;
            case '3': this.itemType = '15'; break;
        }
        if (!node.parentTableName) this.dynamicNodeForm.$('supnodefield').onChange('id', 'id', 'id');
        each(dynamicNodeFieldKeys, action((value, key) => {
            if (key === 'hrmresource') {
                const datas = node.hrmresource && node.hrmresource.valueObj || [];
                this.dynamicNodeForm.$('hrmresource').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmdepartment') {
                const datas = node.hrmdepartment && node.hrmdepartment.valueObj || [];
                this.dynamicNodeForm.$('hrmdepartment').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmsubcompany') {
                const datas = node.hrmsubcompany && node.hrmsubcompany.valueObj || [];
                this.dynamicNodeForm.$('hrmsubcompany').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'rootids') {
                const datas = node.operatorType === '3' ? node.rootids : ''
                this.dynamicNodeForm.$('rootids').onChange(datas);
            } else if (key === 'tablename' || key === 'tablekey' || key === 'showfield' || key === 'hrmField' || key === 'tablesup' || key === 'supnodefield' || key === 'nodefield') {
                const datas = node[key];
                this.dynamicNodeForm.$(key).onChange(datas, datas, [{ id: datas, name: datas }]);
            } else {
                this.dynamicNodeForm.$(key).set(node[value]);
            }
        }));
        this.initOperatorTable();
    }
    @action changeItemType = (value) => {
        this.itemType = value;
        this.initOperatorForm();
    }
    @action initOperatorForm = () => {
        this.operatorForm = new WeaForm();
        const typeDetail = formInfo[this.itemType] || {};
        const items = typeDetail.items || [];
        const conditions = [{ defaultshow: true, items }];
        if (items.length > 1 && items[1].conditionType === 'SELECT_LINKAGE') {
            this.operatorForm.add('', { key: 'joblevel' });
            this.operatorForm.add('', { key: 'jobid_dept' });
            this.operatorForm.add('', { key: 'jobid_subcom' });
        }
        this.operatorForm.initFormFields(conditions);
    }
    @action changeNodeType = (value) => {
        this.dynamicNodeForm.$('nodeType').set(value);
        if (value === '0') {
            this.itemType = '0';
        } else if (value === '1') {
            this.dynamicNodeForm.$('operatorType').set('0');
            if (this.parentNodeType === '0') {
                this.dynamicNodeForm.$('relationtype').set('0');
            } else if (this.parentNodeType === '1') {
                this.dynamicNodeForm.$('relationtype').set('1');
            }
            this.itemType = '6';
        }
        this.initOperatorTable();
    }
    @action changeOperatorType = (value) => {
        this.dynamicNodeForm.$('operatorType').set(value);
        switch (value) {
            case '0': this.itemType = '6'; break
            case '1': this.itemType = '7'; break
            case '2': this.itemType = '11'; break
            case '3': this.itemType = '15'; break
        }
        this.initOperatorForm();
    }
    @action initOperatorTable = () => {
        this.initOperatorForm();
        if (this.node.id) API.dynamicOperatorList(this.node.id).then(this.setOperatorTable);
    }
    @action setOperatorTable = (data) => {
        this.operatorDataSource = data.datas;
        //this.disableAll = data.disableAll;
    }
    @action addOperator = () => {
        const rootids = this.getParams().rootids ? this.getParams().rootids : '';
        if (this.checkOperatorParams()) {
            const name = this.operatorForm.getFormDatas().field && this.operatorForm.getFormDatas().field.valueSpan;
            const type = this.getOperatorType();
            const relationtype = this.dynamicNodeForm.$('relationtype').value
            if (relationtype === '0' && (this.itemType === '6' || this.itemType === '7' || this.itemType === '8' || this.itemType === '9' || this.itemType === '11' || this.itemType === '12' || this.itemType === '13' || this.itemType === '16')) {
                let valueSpan = [];
                switch (this.itemType) {
                    case '6': valueSpan = this.dynamicNodeForm.$('hrmresource').valueObj; break;
                    case '16': valueSpan = this.dynamicNodeForm.$('hrmresource').valueObj; break;
                    case '7': valueSpan = this.dynamicNodeForm.$('hrmdepartment').valueObj; break;
                    case '8': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '9': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '11': valueSpan = this.dynamicNodeForm.$('hrmsubcompany').valueObj; break;
                    case '12': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '13': valueSpan = this.operatorForm.$('field').valueObj; break;
                }
                if (valueSpan && valueSpan.length > 0) {
                    const levelString = this.getLevelString();
                    if (levelString === false) {
                        message.error(getLabel('512197', '请输入安全级别'));
                        return;
                    }
                    valueSpan.map(v => {
                        this.operatorDataSource = [...this.operatorDataSource, {
                            key: uniqueId('-'),
                            name: v.name,
                            type: type,
                            levelString: levelString,
                            ...this.operatorForm.getFormParams(),
                            shareType: this.itemType,
                            rootids: v.id
                        }];
                    })
                } else {
                    this.objBrowserErr.showError();
                }
            } else {
                const levelString = this.getLevelString();
                if (levelString === false) {
                    message.error(getLabel('512197', '请输入安全级别'));
                    return;
                }
                this.operatorDataSource = [...this.operatorDataSource, {
                    key: uniqueId('-'),
                    name: name,
                    type: type,
                    levelString: this.getLevelString(),
                    ...this.operatorForm.getFormParams(),
                    shareType: this.itemType,
                    rootids: rootids
                }];
            }
            this.initOperatorForm();
        }
    }
    @action deleteOperator = () => {
        this.selectedRowKeysAllPages.map(key => {
            const index = this.operatorDataSource.findIndex(item => item.key === key);
            if (index !== -1) {
                this.operatorDataSource.splice(index, 1);
                this.operatorDataSource = [...this.operatorDataSource];
            }
        })
        this.selectedRowKeysAllPages = [];
    }
    getParams = () => {
        const values = this.dynamicNodeForm.values();
        const diffs = {};
        each(dynamicNodeFieldKeys, (value, key) => {
            if (values[key] !== 'value' && this.node && values[key] !== this.node[value]) {
                if (key === 'hrmsubcompany' || key === 'hrmdepartment' || key === 'hrmresource' || key === 'rootids') {
                    const { operatorType } = values;
                    const selectedKey = { '0': 'hrmresource', '1': 'hrmdepartment', '2': 'hrmsubcompany', '3': 'rootids' }[operatorType];
                    if (key === selectedKey) {
                        diffs.rootids = values[key]
                    }
                } else {
                    diffs[key] = values[key]
                }
            }
        });
        if (values['sqlWhere']) diffs['sqlWhere'] = WeaTools.Base64.encode(values['sqlWhere'])
        return diffs;
    }
    checkParams = (values, operatorSetType) => {
        let flag = true;
        const { nodeType, relationtype, operatorType, hrmresource, hrmdepartment, hrmsubcompany, tablename, tablekey, showfield, hrmField, isrecursion, tablesup, supnodefield, nodefield } = values
        let toView = true
        if (nodeType === '1' && relationtype === '0') {//指定对象
            if ((operatorType === '0' && hrmresource === '') || (operatorType === '1' && hrmdepartment === '') || (operatorType === '2' && hrmsubcompany === '')) {
                this.objBrowserErr.showError();
                flag = false;
            }
        }
        if (operatorType === '3') {//自定义
            if (typeof tablename === 'string' && tablename.trim() === '') {
                if(toView){
                const dom = ReactDOM.findDOMNode(this.tableNameErr)
                dom.scrollIntoView();
                dom.getElementsByClassName("wea-browser")[0].focus();
                toView = false;
                }
                this.tableNameErr.showError();
                flag = false;
            }
            if (typeof tablekey === 'string' && tablekey.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.tableKeyErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.tableKeyErr.showError();
                flag = false;
            }
            if (typeof showfield === 'string' && showfield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.showFieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.showFieldErr.showError();
                flag = false;
            }
            if (typeof hrmField === 'string' && hrmField.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.hrmFieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.hrmFieldErr.showError();
                flag = false;
            }
            if (isrecursion === '1' && typeof tablesup === 'string' && tablesup.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.tableSupErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.tableSupErr.showError();
                flag = false;
            }

            if (relationtype === '1' && typeof supnodefield === 'string' && supnodefield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.supnodefieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.supnodefieldErr.showError();
                flag = false;
            }
            if (relationtype === '1' && typeof nodefield === 'string' && nodefield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.nodefieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.nodefieldErr.showError();
                flag = false;
            }
        }
        if(operatorSetType != 1 && this.pathType==3 && this.operatorDataSource.length==0){
            message.error(getLabel('502428', '操作者为空'));
            flag = false;
        }
        return flag;
    }
    checkOperatorParams = () => {
        let flag = true;
        const { field, joblevel, jobid_dept, jobid_subcom } = this.operatorForm.getFormParams()
        const shareType = this.itemType;
        if (field === '' && this.browserErr) {
            this.browserErr.showError();
            flag = false;
        }
        if (shareType === '4') {
            if ((joblevel === '0' && jobid_dept === '')) {
                this.browser2Err.showError();
                flag = false;
            } else if ((joblevel === '1' && jobid_subcom === '')) {
                this.browser3Err.showError();
                flag = false;
            }
        }
        return flag;
    }
    getOperatorType = () => {
        let type = '';
        switch (this.itemType) {
            case '0': type = getLabel('502663', '指定人'); break;
            case '1': type = getLabel('502664', '指定部门'); break;
            case '2': type = getLabel('502665', '指定分部'); break;
            case '3': type = getLabel('502666', '指定角色'); break;
            case '4': type = getLabel('502667', '指定岗位'); break;
            case '5': type = getLabel('502668', '所有人'); break;
            case '6': type = getLabel('502669', '本人'); break;
            case '16': type = getLabel('683', '安全级别'); break;
            case '7': type = getLabel('502670', '本部门'); break;
            case '8': type = getLabel('502671', '本部门角色'); break;
            case '9': type = getLabel('502672', '本部门岗位'); break;
            case '11': type = getLabel('30792', '本分部'); break;
            case '12': type = getLabel('502674', '本分部角色'); break;
            case '13': type = getLabel('502675', '本分部岗位'); break;
            case '15': type = getLabel('502677', '人力资源相关字段'); break;
        }
        return type;
    }
    getLevelString = () => {
        let levelString = "";
        if (this.operatorForm.getFormDatas().level) {
            const minNum = this.operatorForm.getFormDatas().level.value[0] === 0 ? "0" : this.operatorForm.getFormDatas().level.value[0];
            const maxNum = this.operatorForm.getFormDatas().level.value[1] === 0 ? "0" : this.operatorForm.getFormDatas().level.value[1];
            if (!minNum && !maxNum) {
                // 这五种情况是安全级别必填
                if (this.itemType === '1' || this.itemType === '2' || this.itemType === '5' || this.itemType === '7' || this.itemType === '11'|| this.itemType === '16') {

                    return false;
                }
                levelString = "";

            } else if (!minNum && maxNum) {
                levelString = "≤" + maxNum;
            } else if (!maxNum && minNum) {
                levelString = "≥" + minNum;
            } else {
                levelString = this.operatorForm.getFormDatas().level.value[0] + '~' + this.operatorForm.getFormDatas().level.value[1];
            }
        }
        switch (this.itemType) {
            case '3':
                const rolelevel = this.operatorForm.getFormParams().rolelevel;
                levelString = rolelevel === '0' ? getLabel(502298, "部门") : rolelevel === '1' ? getLabel(502299, "分部") : getLabel('140', '总部');
                break;
            case '4':
                const joblevel = this.operatorForm.getFormParams().joblevel;
                levelString = joblevel === '0' ? getLabel('502664', '指定部门') + '(' + this.jobid_deptName + ')' : joblevel === '1' ? getLabel('502665', '指定分部') + '(' + this.jobid_subcomName + ')' : getLabel('140', '总部');
                break;
        }
        return levelString;
    }
    /**动态节点信息相关 end*/

}